package com.promis.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.MediaStore;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by Administrator on 2017/8/14.
 */

public class BitmapUtils {

    public static Bitmap zoomBitmap(Bitmap bmp, int w, int h) {
        if (bmp != null) {
            int width = bmp.getWidth();
            int height = bmp.getHeight();

            Matrix matrix = new Matrix();
            float scaleWidth = ((float) w / width);
            float scaleHeight = ((float) h / height);
            if (scaleWidth > scaleHeight) {
                matrix.postScale(scaleWidth, scaleWidth);
            } else {
                matrix.postScale(scaleHeight, scaleHeight);
            }
            return Bitmap.createBitmap(bmp, 0, 0, width, height, matrix, true);
        } else return null;
    }

    public static Bitmap zoomBitmap(Context context, int resId) {
        Bitmap bmp = getBitmap(context, resId);
        return zoomBitmap(bmp, bmp.getWidth(), bmp.getHeight());
    }

    public static Bitmap getBitmap(Context context, int resId) {
//		return BitmapFactory.decodeResource(resources, resId);
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
        opt.inPurgeable = true;
        opt.inInputShareable = true;
//        opt.inSampleSize = 10;
        //获取资源图片
        InputStream is = context.getResources().openRawResource(resId);
        return BitmapFactory.decodeStream(is, null, opt);
    }

    public static Bitmap drawableToBitmap(Drawable drawable) {
        // 取 drawable 的长宽
        int w = drawable.getIntrinsicWidth();
        int h = drawable.getIntrinsicHeight();

        // 取 drawable 的颜色格式
        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                : Bitmap.Config.RGB_565;
        // 建立对应 bitmap
        Bitmap bitmap = Bitmap.createBitmap(w, h, config);
        // 建立对应 bitmap 的画布
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, w, h);
        // 把 drawable 内容画到画布中
        drawable.draw(canvas);
        return bitmap;
    }

    public static Bitmap bytes2Bimap(byte[] b) {
        if (b.length != 0) {
            return BitmapFactory.decodeByteArray(b, 0, b.length);
        } else {
            return null;
        }
    }

    public static byte[] bitmap2Bytes(Bitmap bm) {
        return bitmap2Bytes(bm, 100);
    }

    public static byte[] bitmap2Bytes(Bitmap bm, int compress) {
        ByteArrayOutputStream baos = null;
        try {
            baos = new ByteArrayOutputStream();
            bm.compress(Bitmap.CompressFormat.PNG, compress, baos);
            return baos.toByteArray();
        } finally {
            if (baos != null)
                try { baos.close(); } catch (IOException e) { e.printStackTrace(); }
        }
    }

    public static void bitmap2File(Bitmap bm, File file) {
        bitmap2File(bm, 100, file);
    }

    public static void bitmap2File(Bitmap bm, int compress, File file) {
        BufferedOutputStream out = null;
        try {
            out = new BufferedOutputStream(new FileOutputStream(file));
            bm.compress(Bitmap.CompressFormat.PNG, compress, out);
            out.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (out != null) try { out.close(); } catch(IOException ioe) {ioe.printStackTrace();}
        }
    }

    /**
     * 获取圆角图片
     * @param bitmap
     * @param roundPx
     * @return
     */
    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        Bitmap output = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, w, h);
        final RectF rectF = new RectF(rect);
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);

        return output;
    }

    /**
     * 获取带倒影的图片
     * @param bitmap
     * @return
     */
    public static Bitmap createReflectionImageWithOrigin(Bitmap bitmap) {
        final int reflectionGap = 4;
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();

        Matrix matrix = new Matrix();
        matrix.preScale(1, -1);

        Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0, h / 2, w,
                h / 2, matrix, false);

        Bitmap bitmapWithReflection = Bitmap.createBitmap(w, (h + h / 2),
                Bitmap.Config.ARGB_8888);

        Canvas canvas = new Canvas(bitmapWithReflection);
        canvas.drawBitmap(bitmap, 0, 0, null);
        Paint deafalutPaint = new Paint();
        canvas.drawRect(0, h, w, h + reflectionGap, deafalutPaint);

        canvas.drawBitmap(reflectionImage, 0, h + reflectionGap, null);

        Paint paint = new Paint();
        LinearGradient shader = new LinearGradient(0, bitmap.getHeight(), 0,
                bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff,
                0x00ffffff, Shader.TileMode.CLAMP);
        paint.setShader(shader);
        // Set the Transfer mode to be porter duff and destination in
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
        // Draw a rectangle using the paint with our linear gradient
        canvas.drawRect(0, h, w, bitmapWithReflection.getHeight()
                + reflectionGap, paint);

        return bitmapWithReflection;
    }

    public static Bitmap getBitmapByUri(Context context, Uri uri) {
        try {
            return MediaStore.Images.Media.getBitmap(context.getContentResolver(), uri);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取旋转后的图片
     * @param context
     * @param resId
     * @param angle
     * @return
     */
    public static Bitmap rotateBitmap(Context context, int resId, float angle) {
        Bitmap bitmap = ((BitmapDrawable) context.getResources().getDrawable(resId)).getBitmap();
        Matrix matrix = new Matrix();
        // 设置旋转角度
        matrix.setRotate(angle);
        // 重新绘制Bitmap
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }

    public static boolean equals(Bitmap bmp1, Bitmap bmp2) {
        if (bmp1.getWidth() == bmp2.getWidth() && bmp1.getHeight() == bmp2.getHeight()) {
            int width = bmp1.getWidth();
            int height = bmp1.getHeight();
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    if (bmp1.getPixel(x, y) != bmp2.getPixel(x, y))
                        return false;
                }
            }
            return true;
        } else return false;
    }

    public static Bitmap getBitmapFromAsset(Context context, String fileName) {
        InputStream is = null;
        try {
            is = context.getAssets().open(fileName);
            return BitmapFactory.decodeStream(is);
        } catch (Exception e) {
            return null;
        } finally {
            if (is != null) try {is.close();} catch(IOException ex) {}
        }
    }

    public static Bitmap eraseBg(Bitmap bitmap, int color) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        Bitmap b = bitmap.copy(Bitmap.Config.ARGB_8888, true);
        b.setHasAlpha(true);

        int[] pixels = new int[width * height];
        bitmap.getPixels(pixels, 0, width, 0, 0, width, height);

        for (int i = 0; i < width * height; i++) {
            if (pixels[i] == color) {
                pixels[i] = 0;
            }
        }

        b.setPixels(pixels, 0, width, 0, 0, width ,height);
        return b;
    }

//    public static String createGif(String filename, List<String> paths, int fps) throws IOException {
//
//        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//        AnimatedGifEncoder localAnimatedGifEncoder = new AnimatedGifEncoder();
//        localAnimatedGifEncoder.start(baos);//start
//        localAnimatedGifEncoder.setRepeat(0);//设置生成gif的开始播放时间。0为立即开始播放
//        localAnimatedGifEncoder.setDelay(fps);
//        if (paths.size() > 0) {
//            for (int i = 0; i < paths.size(); i++) {
//                Bitmap bitmap = BitmapFactory.decodeFile(paths.get(i));
////                Bitmap resizeBm = ImageUtil.resizeImage(bitmap, width, height);
////                localAnimatedGifEncoder.addFrame(resizeBm);
//                localAnimatedGifEncoder.addFrame(bitmap);
//            }
//        }
//        localAnimatedGifEncoder.finish();//finish
//
//        File file = new File(Environment.getExternalStorageDirectory().getPath() + "/LiliNote");
//        if (!file.exists()) file.mkdir();
//        String path = Environment.getExternalStorageDirectory().getPath() + "/LiliNote/" + filename + ".gif";
//        FileOutputStream fos = new FileOutputStream(path);
//        baos.writeTo(fos);
//        baos.flush();
//        fos.flush();
//        baos.close();
//        fos.close();
//
//        return path;
//    }
}
